package com.wehaicao.wehaicaoshardingjdbc.init;

import com.alibaba.druid.pool.DruidDataSource;
import com.wehaicao.wehaicaoshardingjdbc.config.ShardingJdbcProperties;
import com.wehaicao.wehaicaoshardingjdbc.constant.ShardingJdbcConstant;
import org.apache.commons.lang3.StringUtils;


public class DataSourceDirector {

    public static void buildDataSource(DruidDataSource dataSource ,ShardingJdbcProperties shardingJdbcProperties){

//    # 打开PSCache，并且指定每个连接上PSCache的大小
//        poolPreparedStatements: false
//        maxPoolPreparedStatementPerConnectionSize: 20
//    # 配置监控统计拦截的filters，去掉后监控界面sql无法统计，'wall'用于防火墙
//        filters: stat,wall,log4j
//    # 通过connectProperties属性来打开mergeSql功能；慢SQL记录
//        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
//    # 合并多个DruidDataSource的监控数据
//    #spring.datasource.useGlobalDataSourceStat=true
        dataSource.setDriverClassName(shardingJdbcProperties.getDriverClassName());
        dataSource.setDbType(ShardingJdbcConstant.DRUID_TYPE);
        // # 连接池的配置信息
        // # 初始化大小，最小等待连接数量，最大连接数
        dataSource.setInitialSize(shardingJdbcProperties.getInitialSize()==0?5:shardingJdbcProperties.getInitialSize());
        dataSource.setMinIdle(shardingJdbcProperties.getMinIdle()==0?5:shardingJdbcProperties.getMinIdle());
        dataSource.setMaxActive(shardingJdbcProperties.getMaxActive()<5?5:shardingJdbcProperties.getMaxActive());
        // # 配置获取连接等待超时的时间
        dataSource.setMaxWait(shardingJdbcProperties.getMaxWait()==0?6000:shardingJdbcProperties.getMaxWait());
        // # 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(shardingJdbcProperties.getTimeBetweenEvictionRunsMillis()==0?6000:shardingJdbcProperties.getTimeBetweenEvictionRunsMillis());
        // # 配置一个连接在池中最小生存的时间，单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(shardingJdbcProperties.getMinEvictableIdleTimeMillis()==0?300000:shardingJdbcProperties.getMinEvictableIdleTimeMillis());
        dataSource.setValidationQuery(StringUtils.isBlank(shardingJdbcProperties.getValidationQuery())?ShardingJdbcConstant.DB_DEFAULT_SQL:shardingJdbcProperties.getValidationQuery());
        dataSource.setTestWhileIdle(shardingJdbcProperties.getTestWhileIdle()==null?Boolean.TRUE:shardingJdbcProperties.getTestWhileIdle());
        dataSource.setTestOnBorrow(shardingJdbcProperties.getTestOnBorrow()==null?Boolean.FALSE:shardingJdbcProperties.getTestOnBorrow());
        dataSource.setTestOnReturn(shardingJdbcProperties.getTestOnReturn()==null?Boolean.FALSE:shardingJdbcProperties.getTestOnReturn());
    }
}
